<template>
  <!-- 工具库 -->
  <div>
    <div class="title_info">
      <div class="project">工具库</div>
      <search
        ref="tableRef"
        :fields="state.fields"
        @searchList="searchList"
        @resetList="resetList"
        class="m-l20"
        style="flex: 1"
      ></search>
      <div class="head-btn">
        <el-button @click="updataHandler" class="button_edit"> 上传 </el-button>
        <el-button @click="toPathHandler" class="button_edit">
          分类管理
        </el-button>
      </div>
    </div>
    <div class="main_sty">
      <div class="tree_sty">
        <el-tree
          v-if="state.data.length"
          :data="state.data"
          default-expand-all
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
        >
          <template #default="{ data }">
            <span class="custom-tree-node">
              <!-- <span>{{ data.departmentName }}</span> -->
              <span>{{ data["categoryName"] }}</span>
            </span>
            <span
              class="custom-tree-node-show"
              v-if="categoryId == data['categoryId']"
            >
              <CaretRight
                style="
                  width: 1em;
                  height: 1em;
                  margin-right: 8px;
                  color: #fc7018;
                "
              ></CaretRight>
            </span>
          </template>
        </el-tree>
        <el-empty v-else description="暂无数据" />
      </div>
      <div class="list-box">
        <div style="padding-left: 15px; margin-bottom: 10px">
          <el-switch
            v-model="isActive"
            active-text="卡片"
            inactive-text="列表"
          />
        </div>
        <div v-if="isActive" class="research_report_box">
          <div
            style="width: 100%"
            class="research_report"
            v-if="state.filePageList && state.filePageList.length > 0"
          >
            <el-card
              class="box-card"
              v-for="(v, i) in state.filePageList"
              :key="i"
            >
              <div class="title">{{ v.fileName || "暂无" }}</div>
              <div class="department">
                <div>
                  <svg-icon icon-class="department-icon" class="m-r5" />
                  {{ v.departmentName }}
                </div>
                <div>
                  <svg-icon icon-class="user-icon" class="m-r5" />
                  {{ v.userName }}
                </div>
              </div>
              <div class="time">
                <svg-icon icon-class="date-icon" class="m-r5" />
                <span style="color: #b3b3b3">
                  {{ v.createTime || "0000-00-00" }}
                </span>
              </div>
              <el-divider></el-divider>
              <div class="people">
                <div class="donwloadAll">{{ v.downloadNum }}人已下载</div>
                <div class="svg_sty">
                  <svg-icon
                    class="mgl mgr"
                    @click="updataHandel(v)"
                    icon-class="download-icon"
                  />
                  <svg-icon
                    class="mgr"
                    @click="deleteHandel(v)"
                    icon-class="delete-icon"
                  />
                </div>
              </div>
            </el-card>
          </div>
          <el-empty v-else description="暂无数据" style="width: 100%" />
        </div>
        <div v-else class="research_report_box px-10">
          <public-table
            height="550px"
            ref="tableRef"
            :is-paging="false"
            :page="pageParam"
            :table-data="state.filePageList"
            :table-option="tableOption"
          >
            <template #operate="scope">
              <div class="operate">
                <svg-icon
                  class="m-r10"
                  @click="updataHandel(scope.row)"
                  icon-class="download-icon"
                />
                <svg-icon
                  @click="deleteHandel(scope.row)"
                  icon-class="delete-icon"
                />
              </div>
            </template>
          </public-table>
        </div>
      </div>
      <div class="operation_record">
        <blockComponents :msg="'操作记录'"></blockComponents>
        <div class="record-box">
          <template
            v-if="state.downloadLogList && state.downloadLogList.length"
          >
            <div
              class="operation"
              v-for="(item, index) in state.downloadLogList"
              :key="index"
            >
              <div class="img_sty m-r5">
                <img src="@/assets/iconImg/zujin.png" alt="" />
              </div>
              <div class="text">
                <div>
                  <span class="font_sty">{{ item.userName }}</span>
                  <span class="px-10" style="color: #666666">{{
                    ["", "上传", "下载", "删除"][item.type]
                  }}</span>
                  <a class="font_sty" href="#">{{ item.fileName }}</a>
                </div>
                <div class="time">
                  <svg-icon icon-class="date-icon" />
                  <span style="color: #b3b3b3">{{ item.operateTime }}</span>
                </div>
              </div>
            </div>
          </template>
          <el-empty v-else description="暂无数据" />
        </div>
      </div>
    </div>

    <public-dialog
      :title="'上传'"
      :width="'30%'"
      :confirmButtonTitle="'确定'"
      v-model:visible="visible"
      :footerButton="false"
      @onConfirm="onConfirm"
    >
      <el-form :model="dialogForm" ref="formRef" label-width="100px">
        <el-form-item
          label="所属分类"
          :rules="{
            required: true,
            message: '请输入分类名称',
          }"
          prop="catId"
        >
          <el-cascader
            v-model="dialogForm.catId"
            :options="state.options"
            :show-all-levels="false"
            :props="{
              emitPath: false,
            }"
          />
        </el-form-item>
        <el-form-item label="文件上传">
          <el-upload
            ref="upload"
            v-if="visible"
            class="upload-demo"
            :before-upload="beforeUpload"
            :http-request="uploadFile"
            :disabled="!dialogForm.catId"
          >
            <template #trigger>
              <el-button :disabled="!dialogForm.catId">选择文件</el-button>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
    </public-dialog>
  </div>
</template>
<script setup>
import {
  ElButton,
  ElTree,
  ElCard,
  ElIcon,
  ElLoading,
  ElMessage,
  ElForm,
  ElCascader,
  ElUpload,
  ElEmpty,
  ElDivider,
  ElSwitch,
} from "element-plus";
import "@/views/constructionProjectManage/static/button.scss";
import Search from "@/components/table/search.vue";
import { CaretRight } from "@element-plus/icons-vue";
import BlockComponents from "@/components/block_components/index.vue";
import { toolApi } from "@/api/investment.js";
import PublicDialog from "@/components/PublicDialog.vue";

import { reactive, ref, onMounted, onBeforeMount, watch } from "vue";

import { useRouter } from "vue-router";
import PublicTable from "@/components/PublicTable.vue";

import { exportToFile, fileTypeMap } from "@/hooks/useCommon";
const router = useRouter();

const visible = ref(false);
const dialogForm = ref({
  catId: "",
  loaing: false,
});

const isActive = ref(true);

const state = reactive({
  data: [],
  fields: [
    {
      key: "keyword",
      label: "文件名称",
      type: "input",
      placeholder: "请输入文件名称",
    },
    { key: "startTime-endTime", label: "上传时间", type: "datetimerange" },
  ],
  options: [],
});

let pageParam = reactive({
  total: 0,
  current: 1,
  size: 20,
});

const tableOption = ref([
  {
    prop: "fileName",
    label: "文件名称",
    overHidden: false,
    width: 300,
  },
  {
    prop: "departmentName",
    label: "所属分类",
    minWidth: 100,
  },
  {
    prop: "userName",
    label: "上传人",
    minWidth: 60,
  },
  {
    prop: "createTime",
    label: "上传时间",
    minWidth: 100,
  },
  {
    prop: "downloadNum",
    label: "下载次数",
    minWidth: 80,
  },
  {
    prop: "operate",
    label: "操作",
    slot: true,
    minWidth: 50,
  },
]);

const getCogList = () => {
  toolApi.getCogList().then((res) => {
    if (res.code === "200") {
      state.downloadLogList = res.data;
    }
  });
};

const tableRef = ref(null);
const categoryId = ref(null);
const handleNodeClick = (data) => {
  categoryId.value = data.categoryId || "";
  const obj = {
    ...tableRef.value.getSearchParams(),
  };
  getFilePageList(obj);
};

const searchList = (e) => {
  getFilePageList(e);
};

const resetList = (e) => {
  // categoryId.value = "";
};

/**
 * @description: 跳转分类管理
 * @return {*}
 */
const toPathHandler = () => {
  router.push({
    path: "/investmentProjectManagement/toolLibraryManagement/classificationManagement",
  });
};

/**
 * @description: 上传
 * @return {*}
 */
const updataHandler = () => {
  dialogForm.value = {};
  visible.value = true;
};

watch(
  () => visible.value,
  (value) => {
    if (!value) {
      dialogForm.value = {};
    }
  }
);

const formRef = ref(null);
const beforeUpload = () => {
  let flag = true;
  formRef.value.validate((valid) => {
    if (valid) {
      flag = true;
    } else {
      flag = false;
    }
  });

  return flag;
};

const uploadFile = (file) => {
  const loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  let uploadFile = new FormData();
  uploadFile.append("file", file.file);
  uploadFile.append("catId ", dialogForm.value.catId);
  toolApi.upload(uploadFile).then((res) => {
    if (res.code === "200") {
      loading.close();
      ElMessage.success("上传成功!");
      dialogForm.value.urlKey = res.data;
      visible.value = false;
      getFilePageList();
    }
  });
};

const getFilePageList = (param) => {
  toolApi
    .getToolList({
      pageNum: 1,
      pageSize: 10,
      param: {
        ...param,
        catId: categoryId.value,
      },
    })
    .then((res) => {
      if (res.code === "200") {
        state.filePageList = res.data.content;
      }
    });
};

/**
 * @description: 下载
 * @return {*}
 * @param item
 */
const updataHandel = (item) => {
  // fileCallback(item);
  toolApi
    .toolDownload({
      urlKey: item.fileUrlKey,
      catId: item.categoryId,
    })
    .then((res) => {
      exportToFile(res.data, item.fileName);
      getFilePageList();
      getCogList();

      //   return;
      //   let blob = new Blob([res], {
      //     type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
      //   });
      //   console.log(res);
      //   let a = document.createElement("a");
      //   a.href = URL.createObjectURL(blob);
      //   a.download = item.fileName;
      //   a.click();
      //   URL.revokeObjectURL(a.href);
      //   a.remove();
      //   getFilePageList();
      //   getCogList();
    });
};

/**
 * @description: 删除
 * @return {*}
 * @param item
 */
const deleteHandel = (item) => {
  toolApi
    .toolDelete({
      urlKey: item.fileUrlKey,
      catId: item.categoryId,
    })
    .then((res) => {
      if (res.code === "200") {
        ElMessage.success("删除成功");
        setTimeout(() => {
          getFilePageList();
          getCogList();
        }, 1000);
      }
    });
};

//获取项目类型
const getCatList = () => {
  toolApi.getCatList().then((res) => {
    if (res.code === "200") {
      state.data = res.data;
      state.options = res.data.map((v) => {
        return {
          value: v.categoryId,
          label: v.categoryName,
          children: v.children?.map((v2) => {
            return {
              value: v2.categoryId,
              label: v2.categoryName,
            };
          }),
        };
      });
    }
  });
};

onMounted(() => {
  getCatList();
  searchList();
  getCogList();
});
onBeforeMount(() => {});
</script>
<style lang="scss" scoped>
.projectPeople {
  color: #fff;
  cursor: pointer;

  text-align: center;
  font-size: 12px;
  height: 20px;

  line-height: 20px;
  margin-left: 20px;
  background-color: #d4ae85;
  border-radius: 10px;
  padding-left: 5px;
  padding-right: 5px;
}
.title_info {
  display: flex;
  // justify-content: space-between;
  .project {
    width: 15%;
    height: 40px;
    text-align: center;
    line-height: 40px;
    border-radius: 6px;
    font-size: 14px;
    font-family: SourceHanSansMedium, SourceHanSansCN;
    font-weight: bold;
    color: #1a1a1a;
    border: 1px solid #e3e7f1;
  }
}
.main_sty {
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
  .tree_sty {
    width: 15%;
    .el-tree {
      border: 1px solid #e3e7f1;
      border-radius: 6px;
      padding: 15px 10px;
    }
  }
}

.list-box {
  flex: 1;
}
.research_report_box {
  flex: 1;
  .research_report {
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    .box-card {
      --ww: calc((100% - 30% * 3) / 3 / 2);
      width: 30%;
      margin: 0 var(--ww) 20px;
      // height: 160px;
      background: #ffffff;
      box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.03);
      border-radius: 12px;
      border: none;
      .title {
        font-size: 17px;
        font-family: SourceHanSansMedium, SourceHanSansCN;
        color: #000000;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        -o-text-overflow: ellipsis;
      }
      .time {
        color: #666666;
        font-size: 14px;
        margin-top: 10px;
      }
      .department,
      .people {
        margin-top: 15px;
        color: #666666;
        font-size: 14px;
        display: flex;
        justify-content: space-between;
        .donwloadAll {
          width: 200px;
        }
        .svg_sty {
          width: 61px;
          box-sizing: border-box;
          svg {
            margin-left: 10px;
            cursor: pointer;
          }
          // .mgr {
          //   margin-right: 10px;
          //   cursor: pointer;
          // }
        }
      }
    }
  }
}

.operation_record {
  width: 20%;
  .record-box {
    border-radius: 12px;
    border: 1px solid #e3e7f1;
    margin-top: 10px;
  }
}
.font_sty {
  color: #d4ae85;
}
.operation {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-family: SourceHanSansMedium, SourceHanSansCN;
  margin: 0px 10px;
  padding: 15px 0;
  border-bottom: 1px solid #e3e7f1;
  &:last-child {
    border: none;
  }
  .text {
    width: calc(100% - 40px);
    padding-left: 10px;
  }
}
.img_sty {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  img {
    width: 100%;
    height: 100%;
  }
}
.custom-tree-node-show {
  margin-left: 10px;
}
:deep(.el-cascader) {
  width: 100%;
}
.time {
  font-size: 12px;
  font-family: PingFangSC-Regular, PingFang SC;
  color: #b3b3b3;
  margin-top: 10px;
}

:deep(.el-divider) {
  margin: 15px 0;
}
:deep(.el-card) {
  .el-card__body {
    padding-top: 15px;
    padding-bottom: 25px;
  }
}
</style>
